package com.erp.filter;

import com.erp.bean.Log;
import com.erp.bean.User;
import com.erp.conf.Constant;
import com.erp.service.LogService;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * 日志过滤器
 *
 * @Author tj
 * @Date 2022-05-11 16:26:07
 */
public class LogFilter implements Filter {
    LogService logService = new LogService();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 记录日志
        HttpServletRequest request = (HttpServletRequest) servletRequest;// 记录登录日志保存到数据库
        // todo
        Log loginLog = new Log();
        String username = null;
        if (request.getRequestURI().contains("doLogin")) {
            username = request.getParameter("username");
        } else if (!isContainsUrl(request.getRequestURI())) {
            try {
                username = ((User) request.getSession().getAttribute("user")).getUsername();
            }catch (Exception e){}
        }
        loginLog.setUsername(username);
        loginLog.setTime(LocalDateTime.now());
        loginLog.setIp(request.getRemoteAddr().equals("0:0:0:0:0:0:0:1")
                ? "127.0.0.1" : request.getRemoteAddr());
        loginLog.setUrl(request.getRequestURI());
        loginLog.setBrowser(request.getHeader("User-Agent"));
        loginLog.setType(request.getRequestURI().contains("doLogin") ? 10 : 20);
        // 保存数据
        try {
            logService.saveLog(loginLog);
        } catch (Exception e) {
            e.printStackTrace();
        }


        // 请求放行
        filterChain.doFilter(servletRequest, servletResponse);

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    private boolean isContainsUrl(String url) {
        boolean isExist = false;
        for (String item : Constant.notAuthResource) {
            if (url.contains(item)) {
                isExist = true;
            }
        }
        return isExist;
    }
}